import requests
import re
import openpyxl


def get_station_code():
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9343'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36'
    }
    resp = requests.get(url=url, headers=headers)
    resp.encoding = 'utf-8'
    # print(resp.text)
    stations = re.findall('([\u4e00-\u9fa5]+)\|([A-Z]+)', resp.text)
    print(len(stations))
    # for station in stations:
    #     print(station)
    return stations


def save(lst):
    wb = openpyxl.Workbook()
    ws = wb.active
    for item in lst:
        ws.append(item)
    wb.save('车站代码.xlsx')
    print("车站代码已保存")


if __name__ == '__main__':
    save(get_station_code())
